package com.definity.toolkit.web.taglib;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

public class MultipleListTag extends BaseTag {

	private static final long serialVersionUID = 2210901539434005789L;

	private String propertyName;
	private String propertyLabel;
	private String propertyValue;
	private String label;
	private String url;
	private Collection<Object> value;

	
	public MultipleListTag() {

	}
	
	public void setPropertyName(String propertyName) {
		this.propertyName = propertyName;
	}
	
	public void setPropertyLabel(String propertyLabel) {
		this.propertyLabel = propertyLabel;
	}
	
	public void setPropertyValue(String propertyValue) {
		this.propertyValue = propertyValue;
	}
	
	public void setLabel(String label) {
		this.label = label;
	}
	
	public void setUrl(String url) {
		this.url = url;
	}
	
	public void setValue(Collection<Object> value) {
		this.value = value;
	}
	
	@Override
	public int doEndTag() throws JspException {
		StringBuilder html = new StringBuilder();

		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		
		html.append("<div " + createStyleClass("multiple-list") + " propertyName=\"" + propertyName + "\" propertyValue=\"" + propertyValue + "\">");
		
		html.append("<div class=\"insert-box\">");
		html.append("<input type=\"text\" name=\"insertValue\" class=\"autocomplete large common_field value\" url=\"" + url + "\">");
		html.append("<input type=\"button\" value=\"" + i18n().tl("button.add") + "\" class=\"btn action_button\" />");
		html.append("</div>");
		
		html.append("<table class=\"result\" cellspacing=\"0\" cellpadding=\"0\">");
		html.append("<thead>");
		html.append("<tr>");
		html.append("<th colspan=\"2\">");
		html.append(i18n().tl(propertyLabel));
		html.append("</th>");
		html.append("</tr>");
		html.append("</thead>");
		html.append("<tbody>");

		if (value != null) {
			int i = 0;
			for (Object object : value) {
				html.append("<tr>");
				html.append("<td>");
				html.append(valueToString(getValue(object, label)));
				html.append("</td>");
				html.append("<td class=\"center small\">");
				html.append("<a href=\"#\" class=\"deleteItem\">");
				html.append("<img src=\"" + request.getContextPath() + "/resources/images/trash.png\" />");
				html.append("</a>");
				html.append("</td>");
				html.append("<td class=\"hide\">");
				html.append("<input type=\"hidden\" name=\"" + propertyName + "[" + i++ + "]." + propertyValue + "\" value=\"" + valueToString(getValue(object, propertyValue)) + "\" />");
				html.append("</td>");
				html.append("</tr>");
			}
		}

		html.append("</tbody>");
		html.append("</table>");
		html.append("</div>");
		
		write(html);
		
		return super.doEndTag();
	}
	
}
